package com.lagou.mq.controller;

import com.lagou.mq.mapper.OrderMapper;
import com.lagou.mq.pojo.Order;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.MessagePropertiesBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
 * @Description TODO
 * @Classname PayController
 * @Date 2021/7/21 20:13
 * @Author ch'ien
 */
@Controller
public class PayController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderMapper orderMapper;

    @GetMapping("")
    public String index(){
        return "index";
    }

    @GetMapping("/order/{id}")
    public String order(@PathVariable String id, Model model) throws UnsupportedEncodingException {

        MessageProperties properies = MessagePropertiesBuilder.newInstance()
                .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                .setContentEncoding(StandardCharsets.UTF_8.toString())
                .build()
                ;

        Message mes = MessageBuilder
                .withBody(id.getBytes(StandardCharsets.UTF_8.toString()))
                .andProperties(properies)
                .build();
        rabbitTemplate.send("ex.order","order",mes);
        model.addAttribute("id",id);
        Order order = new Order();
        order.setOrderNo(id);
        order.setStatus(0);
        orderMapper.save(order);
        return "pay";
    }

    @GetMapping("/pay/{id}")
    public String pay(@PathVariable String id, Model model) {

        Order one = orderMapper.getOneByOrderNo(id);
        if (one == null || Objects.equals(one.getStatus(), 2)){
            List<Order> list = orderMapper.getListForCancel();
            model.addAttribute("list", list);
            return "list";
        }
        one.setStatus(1);
        orderMapper.update(one);
        return "sucessful";
    }
}
